#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Xml;

using octalforty.Componento.ComponentModel.Caching;
using octalforty.Componento.ComponentModel.Installation.Web;
using octalforty.Componento.Shared.SemanticModel;
using octalforty.Componento.Shared.Util;
using octalforty.Componento.Util;

namespace octalforty.Componento.ComponentModel.Installation
{
    [Export(typeof(IRepositoryBrowserService))]
    public class RepositoryBrowserService : IRepositoryBrowserService
    {
        #region Private Fields
        private IHttpRequestFactoryService httpRequestFactory;
        private ICacheManagerService cacheManager;
        private Regex r = new Regex(@"^(?<PackageName>[^/][^\s]+)\s+((?<Version>\d+(\.\d+){0,3}))?\s*(?<Uri>.+)$", RegexOptions.Compiled | RegexOptions.Multiline);
        #endregion

        #region Public Properties
        [Import()]
        public ICacheManagerService CacheManager
        {
            [DebuggerStepThrough]
            get { return cacheManager; }
            [DebuggerStepThrough]
            set { cacheManager = value; }
        }

        [Import()]
        public IHttpRequestFactoryService HttpRequestFactory
        {
            [DebuggerStepThrough]
            get { return httpRequestFactory; }
            [DebuggerStepThrough]
            set { httpRequestFactory = value; }
        }
        #endregion

        public ComponentDescriptor[] GetComponentDescriptors(Uri repositoryUri)
        {
            //
            // Checking cache
            Uri endpointUri = new Uri(repositoryUri, "components.xml");
            CacheEntryInfo cacheEntryInfo = CacheManager.GetCacheEntryInfo(endpointUri.ToString());
            
            IHttpRequest httpRequest = HttpRequestFactory.CreateHttpRequest(HttpMethod.Get, endpointUri);
            if(cacheEntryInfo != null)
                httpRequest.IfModifiedSince = cacheEntryInfo.UpdatedOn;

            using(IHttpResponse httpResponse = httpRequest.GetResponse())
            {
                if(httpResponse.StatusCode == HttpStatusCode.NotModified)
                    using(MemoryStream ms = new MemoryStream(cacheEntryInfo.Content))
                        return ParseRepositoryEntries(ms);
                
                using(Stream responseStream = httpResponse.GetResponseStream())
                {
                    using(MemoryStream memoryStream = new MemoryStream())
                    {
                        StreamUtil.Copy(responseStream, memoryStream);

                        memoryStream.Position = 0;

                        CacheManagerServiceUtil.Add(CacheManager, endpointUri.ToString(), memoryStream);

                        memoryStream.Position = 0;

                        return ParseRepositoryEntries(memoryStream);
                    } // using
                } // using
            } // using
        }

        private static ComponentDescriptor[] ParseRepositoryEntries(Stream responseStream)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(responseStream);

            ComponentDescriptorParser componentDescriptorParser = new ComponentDescriptorParser();
            ComponentDescriptor[] descriptors = 
                componentDescriptorParser.ParseComponentDescriptors(xmlDocument);

            return descriptors;
        }
    }
}